/*
 * HttpMessage.cpp
 *
 */

#include "HttpMessage.h"
#include "HttpHeader.h"
#include "../../common/StrUtils.h"

MessageException::MessageException(const std::string& msg) throw():
msg(msg) {}

const std::string HttpMessage::WHITES = " \t";
const std::string HttpMessage::CRLF = "\r\n";

HttpMessage::HttpMessage() {}

HttpMessage::~HttpMessage() {
	std::list<HttpHeader*>::iterator it;
	for (it = headers.begin(); it != headers.end(); ++it)
		delete *it;
	headers.clear();
}

void HttpMessage::addHeader(HttpHeader* header) {
	headers.push_back(header);
}

void HttpMessage::removeHeader(const std::string& name) {
	bool found = false;
	std::list<HttpHeader*>::iterator it = headers.begin();
	while (it != headers.end() && !found) {
		if (StrUtils::toUpper((*it)->getName()) == StrUtils::toUpper(name)) {
			delete *it;
			headers.erase(it);
			found = true;
		} else
			++it;
	}
	if (!found)
		throw MessageException("Header not found");
}

std::string HttpMessage::getHeader(const std::string& name) const {
	bool found = false;
	std::list<HttpHeader*>::const_iterator it = headers.begin();
	while (it != headers.end() && !found) {
		if (StrUtils::toUpper((*it)->getName()) == StrUtils::toUpper(name))
			found = true;
		else
			 ++it;
	}
	if (!found)
		throw MessageException("Header not found");
	return (*it)->getValue();
}

const std::list<HttpHeader*>& HttpMessage::getAllHeaders() const {
	return headers;
}
